<template>
  <div class="chat">
    <van-nav-bar
      title="安心修智能管家"
      class="nav_bar"
      fixed
      @click-left="onClickLeft"
    />
    <div class="main" ref="scrollContainer">
      <div class="header">
        <van-image
          class="header_icon"
          :src="require('@/assets/icon/home/anxinxiu.png')"
        />
      </div>
      <div class="list">
        <!-- <div v-show="!refreshing" class="historyTips">
          {{ refirshFinish ? "没有更多历史了" : "下拉查看更多历史记录" }}
        </div> -->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" disabled>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text=""
            :immediate-check="false"
          >
            <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->
            <div class="common">
              <div class="chat_item system">
                <van-image
                  class="avatar"
                  fit="cover"
                  round
                  :src="require('@/assets/icon/common/avatar.png')"
                />
                <div class="message">
                  <div class="text_1">HI，我是您的智能养车管家~</div>
                  <div class="text_2">
                    我可以回答您关于【保养项目】、【服务预约】、【故障维修】、【爆胎处理】、【维权投诉】等相关问题。欢迎您随时向我提问哦，快来试试
                  </div>
                </div>
              </div>
              <transition name="van-slide-left">
                <div v-show="showQuestion" class="question_box">
                  <div class="header">
                    <div class="title">为您推荐以下问题</div>
                    <div class="btn">
                      <van-icon
                        name="replay"
                        class="btn_icon"
                        @click="refreshQuestion"
                      />
                      换一换
                    </div>
                  </div>
                  <div class="question_list">
                    <span
                      v-for="(v, i) in questionList"
                      :key="i"
                      class="question_item"
                      :data-index="i"
                      :class="{
                        item_1: i == 0,
                        item_2: i == 1,
                        item_3: i == 2,
                        fadeOut: isExit,
                      }"
                      @click="clickQuestions(v)"
                    >
                      {{ v }}
                    </span>
                  </div>
                </div>
              </transition>
            </div>
            <div
              v-for="(v, i) in list"
              :key="i"
              class="chat_item"
              :class="{ system: v.sendType == 3, user: v.sendType == 1 }"
            >
              <van-image
                class="avatar"
                fit="cover"
                round
                :src="
                  v.sendType == 3
                    ? require('@/assets/icon/common/avatar.png')
                    : v.sendUserAvatar
                "
              />
              <div class="message">
                <div class="text_2">
                  {{ v.text }}
                </div>
              </div>
              <van-loading v-if="v.loading" />
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <div class="input">
      <van-search
        v-model="keyword"
        show-action
        :disabled="searchLoding"
        placeholder="请具体详细的描述你要咨询的汽车问题"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch" class="search_btn">发送</div>
        </template>
      </van-search>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { mapGetters } from "vuex";
import api from "@/api/api";

export default {
  components: {},
  props: {},
  data() {
    return {
      historyList: [],
      list: [],
      loading: false,
      finished: true,
      refreshing: false,
      isExit: false,
      refirshFinish: false,
      showQuestion: false,
      keyword: "",
      questionList: ["保养手册", "雨刮有异响怎么办", "什么品牌的轮胎品质好"],
      pageInfo: {
        pageNum: 1,
        pageSize: 20,
      },
      searchLoding: false,
    };
  },
  watch: {},
  computed: {
    ...mapGetters(["userData"]),
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    onLoad() {
      if (this.refreshing) {
        this.list = [];
        this.refreshing = false;
      }
      this.getMessageList();
    },
    onRefresh() {},
    clickQuestions(v) {
      this.keyword = v;
      this.onSearch();
    },
    async getMessageList() {
      let parmas = {
        ...this.pageInfo,
        storeId: 0,
      };
      let res = await api.getMessageList(parmas);
      this.list = [...this.list, ...res.data].filter(
        (item) => item.type == 0 && !item.loading
      );
      const uniqueMap = new Map(this.list.map((item) => [item.autoId, item]));
      this.list = Array.from(uniqueMap.values());

      this.scrollToBottom(); // 替换原有的$nextTick逻辑
      if (res.data.length < this.pageInfo.pageSize) {
        this.finished = true;
      } else {
        this.pageInfo.pageNum++;
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer;
        if (container.scrollHeight <= container.clientHeight) {
          return; // 内容不足一屏时不滚动
        }
        if (container) {
          // 获取容器实际样式（包含padding）
          const style = window.getComputedStyle(container);
          const paddingBottom = parseFloat(style.paddingBottom) || 0;

          // 计算正确的滚动位置（包含padding补偿）
          const scrollPosition =
            container.scrollHeight - container.clientHeight + paddingBottom;
          // 计算正确的滚动位置：滚动高度 - 容器可视高度 + 底部padding
          container.scrollTo({
            top: scrollPosition,
            behavior: "smooth",
          });
        }
      });
    },
    refreshQuestion() {
      this.isExit = !this.isExit;
      // 自动重置动画
      if (this.isExit) setTimeout(() => (this.isExit = false), 500);
    },
    async onSearch() {
      if (this.searchLoding) return;
      if (this.keyword.trim().length == 0) {
        Toast("咨询的问题不能为空");
      } else {
        this.searchLoding = true;
        let params = {
          accountType: 0,
          storeId: 0,
          text: this.keyword,
          type: 0,
          fileUrl: "",
        };
        this.list.push({
          userId: this.userData.id,
          storeId: params.storeId,
          sendType: 1,
          type: params.type,
          text: this.keyword,
          flleUrl: params.fileUrl,
          sendUserName: this.userData.userName,
          sendUserAvatar: this.userData.avatar,
          createTime: Date.now(),
          loading: true,
        });
        this.scrollToBottom();
        setTimeout(() => {
          this.keyword = "";
        }, 200);
        await api
          .sendMessage(params)
          .catch(() => {
            this.list[this.list.length - 1].loading = false;
            Toast("回答超时，请重新发送");
          })
          .finally(() => (this.searchLoding = false));
        // this.scrollToBottom();
        this.onLoad();
      }
    },
    focusFunction() {
      setTimeout(() => {
        window.scrollTo(0, document.body.sc);
      }, 300); // 等待键盘动画
    },
  },
  created() {},
  mounted() {
    this.onLoad();
    let timer = setTimeout(() => {
      this.showQuestion = true;
      clearTimeout(timer);
    }, 300);
    if (/iOS/i.test(navigator.userAgent)) {
      this.$refs.input.$el.addEventListener("focus", this.focusFunction);
    }
  },
};
</script>
<style lang="less" scoped>
.chat {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/4431a33cd62f4efc9fc53a7606eee382.png")
    no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  box-sizing: border-box;
  padding: 160px 50px 150px 50px;
  box-sizing: border-box; /* 确保padding包含在高度计算内 */
  .main {
    height: calc(100vh - 46px - 70px);
    padding-bottom: 300px;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; // iOS优化
    will-change: transform; // 硬件加速优化
    /* 增加以下属性 */
    scroll-behavior: smooth;
    scroll-padding-bottom: 20px; /* 预留底部空间 */
    contain: layout; /* 防止内容跳动 */

    overscroll-behavior: contain; /* 防止滚动链 */
    .header {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .header_icon {
        width: 190px;
        height: 101px;
      }
    }
    .list {
      margin-top: 30px;
      .historyTips {
        font-size: 32px;
        color: #898989;
        margin-bottom: 50px;
        text-align: center;
      }
      .common {
        margin: 20px 0;
        .question_box {
          margin-top: 80px;
          border: 1px solid #eef4ff;
          padding: 60px 50px;
          background: #eef4ff;
          border-radius: 30px;
          .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .title {
              font-size: 50px;
              color: #406dfc;
            }
            .btn {
              display: flex;
              align-items: center;
              .btn_icon {
                margin-right: 10px;
                font-size: 50px;
              }
              font-size: 38px;
              color: #999999;
            }
          }
          .question_list {
            display: flex;
            flex-direction: column;
            margin-top: 30px;
          }
          .question_item {
            padding: 15px 30px;
            border-radius: 10px;
            color: #fff;
            background: #406dfc;
            font-size: 38px;
            max-width: 500px;
            text-align: center;
            opacity: 0;
            animation: enterAnim 0.8s forwards;
            transform: translateX(-50px);
          }
          .item_1 {
            animation-delay: 0.3s;
          }
          .item_2 {
            margin: 40px 0 40px 20%;
            animation-delay: 0.6s;
          }
          .item_3 {
            margin-left: 40%;
            animation-delay: 0.9s;
          }
        }
      }

      .chat_item {
        display: flex;
        align-items: start;
        width: 100%;
        margin: 40px 0;
        .avatar {
          min-width: 150px;
          max-width: 150px;
          height: 150px;
        }
        .message {
          padding: 30px 25px;
          border-radius: 20px;
          flex-grow: 1;
          max-width: 60%;
          .text_1 {
            font-size: 50px;
            color: #303030;
            font-weight: bold;
            margin-bottom: 20px;
          }
          .text_2 {
            font-size: 38px;
            color: #666666;
          }
        }
      }
      .system {
        justify-content: start;
        .message {
          margin-left: 30px;
          background: #fff;
        }
      }
      .user {
        flex-direction: row-reverse;
        // justify-content: flex-end;
        .message {
          margin-right: 30px;
          background: #406dfc;
          .text_2 {
            color: #fff;
          }
        }
      }
    }
  }

  .input {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30px 30px 90px 30px;
    background: #fff;
    z-index: 99;
    /deep/ .van-search {
      padding: 0;
    }
    .search_btn {
      font-size: 38px;
      padding: 0 40px;
      background: #406dfc;
      border-radius: 10px;
      height: 100px;
      line-height: 100px;
      color: #fff;
    }
  }

  .nav_bar {
    /deep/ .van-icon {
      font-size: 50px;
      font-weight: bold;
      color: #333333;
    }
  }

  /* 退出动画 */
  .fadeOut {
    animation: exit 0.8s !important;
  }

  /* 动画关键帧 */
  @keyframes enterAnim {
    to {
      opacity: 1;
      transform: translateX(calc(20px * var(--index)));
    }
  }

  /* 通过属性选择器设置偏移 */
  .question_item[data-index="0"] {
    --index: 0;
  }
  .question_item[data-index="1"] {
    --index: 1;
  }
  .question_item[data-index="2"] {
    --index: 2;
  }

  @keyframes exit {
    to {
      opacity: 0;
      transform: translateX(calc(100% + 50px * var(--index)));
    }
  }
}
</style>
